package com.zzapp.meizhi.view

import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator

/**
 * Project MeiZhi
 * Date 2017-11-04
 *
 * @author zzzz
 */

class FabBehavior : CoordinatorLayout.Behavior<FloatingActionButton>{

    constructor()

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    private var visible = true

    override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, directTargetChild: View, target: View, nestedScrollAxes: Int): Boolean {
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild,
                target, nestedScrollAxes)
    }

    override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
        if (dyConsumed > 0 && visible) {
            visible = false
            onHide(child)
        } else if (dyConsumed < 0) {
            visible = true
            onShow(child)
        }
    }

    private fun onHide(view: View) {
        ViewCompat.animate(view).translationY((view.getHeight() * 2).toFloat()).interpolator = AccelerateInterpolator(3f)
    }

    private fun onShow(view: View) {
        ViewCompat.animate(view).translationY(0f).interpolator = DecelerateInterpolator(3f)
    }
}